#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "httpmgr.h"
#include "utils.h"

#include <QCheckBox>
#include <QPushButton>
#include <QJsonObject>
#include <QMessageBox>


RegisterDialog::RegisterDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);



    //绑定HttpMgr发射的信号
    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_reg_mod_finish,
            this,&RegisterDialog::slot_reg_mod_finish);

    //设置图标与标题
    this->setWindowTitle(" ");
    this->setWindowIcon(QIcon(":/images/dog_svg.svg"));


    ui->register_btn->setEnabled(false);
    ui->reg_id->setPlaceholderText("请输入账号（仅数字,最大19位）");
    ui->reg_password->setPlaceholderText("请输入密码");
    ui->reg_repassword->setPlaceholderText("再次输入密码");
    ui->reg_mail->setPlaceholderText("请输入您的邮箱");
    ui->reg_veri_code->setPlaceholderText("邮箱验证码");
    ui->reg_password->setEchoMode(QLineEdit::Password);
    ui->reg_repassword->setEchoMode(QLineEdit::Password);

    //设置定时器为1秒，当验证码验证错误达到一定次数时启动
    timer= new QTimer();
    timer->setInterval(1000);
    connect(timer,&QTimer::timeout,this,&RegisterDialog::slot_permit);

    // 创建 QCheckBox 控件（父类选择QLineEdit）,使密码框右侧出现眼睛符号
    QCheckBox *checkBox = new QCheckBox(ui->reg_password);
    checkBox->setCursor(Qt::PointingHandCursor);
    // 设置样式表（图片为眼睛样式），及密码框右边的眼睛符号
    checkBox->setStyleSheet("QCheckBox {spacing: 5px;border: none;background-color: transparent;}"
                            "QCheckBox::indicator {width: 20px;height: 20px;border: none;image: url(:/images/unvisible.png);}"
                            "QCheckBox::indicator:checked {image: url(:/images/visible.png);}");
    //创建信号和槽连接
    connect(checkBox, &QCheckBox::stateChanged,this, &RegisterDialog::slot_checkbox_state_changed);
    //设置控件的位置（需要根据QLineEdit的坐标进行调整）
    checkBox->setGeometry(ui->reg_password->pos().x() + 250,ui->reg_password->pos().y() + 7,20,20);

    //发送验证码按钮 使邮箱输入框右侧出现发送验证码按钮
    verificatioon_code = new QPushButton(ui->reg_mail);
    verificatioon_code->setText("发送验证码");
    verificatioon_code->setCursor(Qt::PointingHandCursor);
    // 设置样式表（图片为眼睛样式）
    verificatioon_code->setStyleSheet("QPushButton {border: none;background-color: transparent;}");
    //创建信号和槽连接
    connect(verificatioon_code, &QPushButton::clicked,this, &RegisterDialog::slot_checkbox_clicked);
    //设置控件的位置（需要根据QLineEdit的坐标进行调整）
    verificatioon_code->setGeometry(ui->reg_mail->pos().x() + 210,ui->reg_mail->pos().y() + 7,65,20);


}



void RegisterDialog::slot_checkbox_state_changed(int state)
{
    if(state){
        ui->reg_password->setEchoMode(QLineEdit::Normal);
        ui->reg_repassword->setEchoMode(QLineEdit::Normal);
    }else{
        ui->reg_password->setEchoMode(QLineEdit::Password);
        ui->reg_repassword->setEchoMode(QLineEdit::Password);
    }
}

void RegisterDialog::slot_checkbox_clicked()
{
    open_slidver_count++;
    //当验证码验证错误达到两次，触发等待30秒后才能再次验证
    if(open_slidver_count>2){
        open_slidver_count= 0;
        verificatioon_code->setEnabled(false);
        timer->start();
        return;
    }

    //创建滑动验证码窗口
    _veri_dlg = new SlidingVerificationDialog(this);
    //完成验证后，滑动验证码窗口将发送信号sig_result，接受信号结果检测验证是否成功
    connect(_veri_dlg,&SlidingVerificationDialog::sig_result,this,&RegisterDialog::slot_slidingverificaton);
    _veri_dlg->show();
}

RegisterDialog::~RegisterDialog()
{
    delete ui;
}

void RegisterDialog::on_radioButton_clicked(bool checked)
{
    ui->register_btn->setEnabled(checked);
}

//验证码倒计时功能
void RegisterDialog::slot_permit()
{
    if(num_time<=0){
        verificatioon_code->setEnabled(true);
        verificatioon_code->setText("发送验证码");
        timer->stop();
        num_time=30;
        return;
    }
    num_time--;
    QString str= QString::asprintf("剩余%d秒",num_time);
    verificatioon_code->setText(str);
}

void RegisterDialog::slot_slidingverificaton(bool result)
{

    //滑动验证窗口验证成功，发送验证码请求
    if(result){
        auto email = ui->reg_mail->text();

        //发送http请求获取验证码
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_varifycode"),
                                            json_obj, ReqId::ID_GET_VARIFY_CODE,Modules::REGISTERMOD);
        QMessageBox::information(this,"验证码已发送","请耐心等待，验证码将发送到您的邮箱");
        return;
    }
    //滑动验证窗口验证失败
    else {
        QMessageBox::critical(this,"错误！","请将拼图正确移动到缺口处！");
        return;
    }
}

//处理http请求回调信息
void RegisterDialog::slot_reg_mod_finish(ReqId id, QByteArray res, ErrorCodes err)
{
    if(err == ErrorCodes::ERR_NETWORK){
        QMessageBox::critical(this,"错误","请求发送失败！");
        return;
    }

    switch (id) {
    //验证码模块
    case ReqId::ID_GET_VARIFY_CODE:
    {
        QString verifycode = QString::fromUtf8(res);//使用编码UTF-8，将res转化为qstring类型
        verifyCode= new VerifyCode(this);//验证码类
        verifyCode->qverifycode = verifycode;//给予验证码值，该类将计时，五分钟后验证码过期清除
        verifyCode->timer->start();
        qDebug() << verifycode;
    }
        break;

    case ReqId::ID_REG_USER:
    {
        QString info = QString::fromUtf8(res);//使用编码UTF-8，将res转化为qstring类型
        QMessageBox::information(this,"",info);
    }
    break;

    default:
        break;
    }
}

//注册按钮
void RegisterDialog::on_register_btn_clicked()
{

    //判断输入账号是否符合规范，即纯数字，不为空，不大于20位
    if(!(isNumeric(ui->reg_id->text())) || (ui->reg_id->text().isEmpty())
        || (ui->reg_id->text().length()>20) ){
        QMessageBox::critical(this,"错误","账号格式错误！");
        return;
    }
    //判断两次密码输入是否相等
    else if(ui->reg_password->text()!=ui->reg_repassword->text()){
        QMessageBox::critical(this,"错误","两次密码输入不一致！");
        return;
    }
    //判断邮箱是否符合格式
    else if(!isQQEmail(ui->reg_mail->text())){
        QMessageBox::critical(this,"错误","邮箱格式错误！");
        return;
    }
    //判断验证码是否有效
    else if(verifyCode->qverifycode.isEmpty()){
        QMessageBox::critical(this,"错误","验证码已失效！");
        return;
    }
    //判断用户输入验证码是否正确
    else if(verifyCode->qverifycode != ui->reg_veri_code->text()){
        QMessageBox::critical(this,"错误","验证码错误！");
        return;
    }



    //发送注册用户请求
    QJsonObject json_obj;
    json_obj["Id"] = ui->reg_id->text().toInt();
    json_obj["Password"] = ui->reg_password->text();
    json_obj["Email"] = ui->reg_mail->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/toRegister"),
                                        json_obj, ReqId::ID_REG_USER,Modules::REGISTERMOD);
}

